<template>
  <div class="app-container  pull-auto">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery">
        <el-form-item label="用户名" prop="username">
          <el-input @keyup.enter.native="handleFilter" size="small" placeholder="用户名" v-model="listQuery.username" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select @keyup.enter.native="handleFilter" style="width: 90px !important" size="small" v-model="listQuery.status" placeholder="状态">
            <el-option value="0" label="有效">有效</el-option>
            <el-option value="1" label="无效">无效</el-option>
            <el-option value="9" label="锁定">锁定</el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter" icon="el-icon-search" size="small">搜索</el-button>
          <el-button @click="searchReset" icon="el-icon-delete" size="small">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="crud-menu">
      <div class="crud-menu_left">
        <el-button v-if="sys_user_add" size="small" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
      </div>
      <div class="crud-menu_right">
        <el-button icon="el-icon-refresh" circle size="small" @click="handleFilter"></el-button>
      </div>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row :default-sort = "{prop: 'id', order: 'descending'}" style="width: 100%">

      <el-table-column align="center" label="序号" width="60" type="index" :index="indexMethod"/>

      <el-table-column align="center" label="用户名">
        <template slot-scope="scope">
          <span>
            <img v-if="scope.row.avatar" class="user-avatar" style="width: 20px; height: 20px; border-radius: 50%;" :src="scope.row.avatar+'?imageView2/1/w/20/h/20'"> {{scope.row.username}}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="所属部门" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.deptName}} </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="角色">
        <template slot-scope="scope">
          <span v-for="role in scope.row.roleList">{{role.roleDesc}} </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="账户有效期">
        <template slot-scope="scope">
          <span>{{scope.row.accountExpired | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="密码有效期">
        <template slot-scope="scope">
          <span>{{scope.row.passwordExpired | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="cdate" align="center" sortable label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="status-col" label="状态" width="75">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilterX">{{scope.row.status | statusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button v-if="sys_user_upd" size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="sys_user_del" size="mini" type="danger" @click="deletes(scope.row)">删除</el-button>
          <el-button v-if="sys_user_pwd" size="mini" type="success" @click="resetPwd(scope.row)">密码重置</el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container pull-right">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogDeptVisible" width="30%">
      <el-tree class="filter-tree" :data="treeDeptData" :default-checked-keys="checkedKeys" check-strictly node-key="id" highlight-current ref="deptTree" :props="defaultProps" @node-click="getNodeData" default-expand-all>
      </el-tree>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输用户名" width="30%"></el-input>
        </el-form-item>

        <el-form-item v-if="dialogStatus == 'create'" label="密码" prop="newpassword1">
          <el-input type="password" v-model="form.newpassword1" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item v-if="dialogStatus == 'create'" label="确认密码" prop="newpasswordCheck">
          <el-input type="password" v-model="form.newpasswordCheck" placeholder="请确认密码"></el-input>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="选择部门" @focus="handleDept()" readonly></el-input>
              <input type="hidden" v-model="form.deptId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select class="filter-item" v-model="role" placeholder="请选择" multiple>
                <el-option v-for="item in rolesOptions" :key="item.roleId" :label="item.roleDesc" :value="item.roleId" :disabled="isDisabled[item.delFlag]">
                  <span style="float: left">{{ item.roleDesc }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roleCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="账户有效期" prop="accountExpired">
              <el-date-picker v-model="form.accountExpired" type="date" format="yyyy-MM-dd" :picker-options="pickerOptions0" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码有效期" prop="passwordExpired">
              <el-date-picker v-model="form.passwordExpired" type="date" format="yyyy-MM-dd" :picker-options="pickerOptions0" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="状态" v-if="dialogStatus == 'update' && sys_user_del " prop="status">
          <el-select class="filter-item" v-model="form.status" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item" :label="item | statusFilter" :value="item"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/user'
import { deptRoleList, fetchDeptTree } from '@/api/role'
import waves from '@/directive/waves/index.js' // 水波纹指令
import { mapGetters } from 'vuex'
import { getToken } from '@/util/auth'
import ElRadioGroup from 'element-ui/packages/radio/src/radio-group'
import ElOption from 'element-ui/packages/select/src/option'
import myUpload from 'vue-image-crop-upload'

export default {
  components: {
    ElOption,
    ElRadioGroup,
    myUpload
  },
  name: 'table_user',
  directives: {
    waves
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (this.form.newpasswordCheck !== '') {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.form.newpassword1) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      treeDeptData: [],
      checkedKeys: [],
      show: false,
      imgDataUrl: '',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      role: [],
      form: {
        username: undefined,
        newpassword1: undefined,
        status: undefined,
        deptId: undefined,
        phone: undefined,
        accountExpired: undefined,
        passwordExpired: undefined
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        newpassword1: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '长度在 6 到 20 个字符',
            trigger: 'blur'
          }
        ],
        newpasswordCheck: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
          },
          { validator: validatePass2, trigger: 'blur' }],
        deptName: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色(先选择部门)',
            trigger: 'blur'
          }
        ],
        accountExpired: [
          {
            required: true,
            message: '请选择账户有效期',
            trigger: 'blur'
          }
        ],
        passwordExpired: [
          {
            required: true,
            message: '请选择密码有效期',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: checkPhone,
            trigger: 'blur'
          }
        ]
      },
      statusOptions: ['0', '1', '9'],
      rolesOptions: [],
      dialogFormVisible: false,
      dialogDeptVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      isDisabled: {
        0: false,
        1: true
      },
      tableKey: 0
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '有效',
        1: '无效',
        9: '锁定'
      }
      return statusMap[status]
    },
    statusFilterX(status) {
      const statusMapX = {
        0: 'success',
        1: 'danger',
        9: 'warning'
      }
      return statusMapX[status]
    }
  },
  created() {
    this.getList()
    this.sys_user_add = this.permissions['sys_user_add']
    this.sys_user_upd = this.permissions['sys_user_upd']
    this.sys_user_del = this.permissions['sys_user_del']
    this.sys_user_pwd = this.permissions['sys_user_pwd']
  },
  methods: {
    indexMethod(index) {
      return (index + 1) + (((this.listQuery.page || 1) - 1) * (this.listQuery.limit || 10))
    },
    getList() {
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getNodeData(data) {
      this.dialogDeptVisible = false
      this.form.deptId = data.id
      this.form.deptName = data.name
      deptRoleList(data.id).then(response => {
        this.rolesOptions = response.data
      })
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data
        this.dialogDeptVisible = true
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      getObj(row.userId).then(response => {
        this.form = response.data
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.role = []
        for (var i = 0; i < row.roleList.length; i++) {
          this.role[i] = row.roleList[i].roleId
        }
        deptRoleList(response.data.deptId).then(response => {
          this.rolesOptions = response.data
        })
      })
    },
    // 搜索清空
    searchReset() {
      this.listQuery = {
        username: '',
        status: ''
      }
    },
    create(formName) {
      const set = this.$refs
      this.form.role = this.role
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      this.form.role = this.role
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    deletes(row) {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.userId)
          .then(data => {
            if (data.data) {
              this.$notify({
                title: '成功',
                showClose: true,
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$notify({
                title: '失败',
                showClose: true,
                message: '删除失败',
                type: 'error'
              })
            }
            this.getList()
          })
          .catch(() => {
            this.$notify({
              title: '异常',
              message: '删除异常',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    resetPwd(row) {
      this.$confirm(
        '此操作将重置用户(用户名:' + row.username + ')密码, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        putObj({ userId: row.userId, newpassword1: '123456' })
          .then(() => {
            this.$notify({
              title: '成功',
              message: '密码重置成功,新密码为[123456],请尽快修改密码',
              type: 'success',
              duration: 3000
            })
          })
          .catch(() => {
            this.$notify({
              title: '失败',
              message: '密码重置失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    resetTemp() {
      this.form = {
        id: undefined,
        username: '',
        password: '',
        role: [],
        status: '',
        deptId: '',
        phone: ''
      }
    }
  }
}
</script>
